<template>
  <div>
    <el-row>
      <el-col>
        <xy-addrole @addRole="addRoled"></xy-addrole>
      </el-col>
    </el-row>
    <el-table :data="roleList" style="width: 100%" border stripe>
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            :class="['bdbuttom', 'vcenter']"
            v-for="menu in scope.row.menus"
            :key="menu.menuId"
          >
            <el-col :span="5" class="vcenter">
              <el-tag closable @close="removeAuthById(scope.row, menu.menuId)">
                {{ menu.name }}
              </el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="19">
              <el-row
                class="bdbuttom vcenter"
                v-for="item2 in menu.subMenus"
                :key="item2.id"
              >
                <el-col :span="6">
                  <el-tag
                    closable
                    type="success"
                    @close="removeAuthById(scope.row, item2.id)"
                  >
                    {{ item2.name }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    v-for="item3 in item2.buttons"
                    closable
                    @close="removeAuthById(scope.row, item3.id)"
                    type="warning"
                    :key="item3.id"
                    >{{ `${item3.name || item2.name}-${item3.method}` }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" width="180" prop="name">
      </el-table-column>
      <el-table-column label="角色描述" prop="desc"> </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <div class="center">
            <el-button
              type="primary"
              circle
              icon="el-icon-edit"
              @click="editRole(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="deleteRole(scope.row)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <!-- <xy-assignper :role="scope.row"></xy-assignper> -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="showSetRightDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="修改角色" :visible.sync="editDlgVisible">
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRoles"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名称" prop="localName">
          <xy-input v-model="editForm.localName" clearable></xy-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <xy-input v-model="editForm.desc"></xy-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDlgVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('editFormRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- #region Dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
    >
      <el-tree
        :data="menu"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSetRightsSubmit('FromRef')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- #endregion -->
  </div>
</template>

<script>
// import roleList from "./rolesdata.js";
// // import authList from "./authdata.js";
// import menu from "../../views/menudata";
import AddRole from "./AddRole";

// import AssignPer from "./AssignPermissions";
export default {
  components: {
    "xy-addrole": AddRole,
    // "xy-assignper": AssignPer,
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (/^[\u4e00-\u9fa5\w]+$/.test(value)) {
        callback();
      } else {
        callback(new Error("输入了无效字符"));
      }
    };
    return {
      apiName: "/api/Roles",
      editDlgVisible: false,
      setRightDialogVisible: false,
      roleList: [],
      editForm: {},
      editFormRoles: {
        userName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            message: "长度在 不小于 2 个字符",
            trigger: "blur",
          },
          {
            max: 10,
            message: "长度在 不大于 10 个字符",
            trigger: "blur",
          },
          { validator: validateName, trigger: "blur" },
        ],
      },
      menu: [],
      //  树形控件的属性绑定对象
      treeProps: {
        label: "name",
        children: "subMenus",
      },
      //   默认选中节点ID值
      defKeys: [],
    };
  },
  created() {
    // console.log(roleList);
    this.getData();
  },
  methods: {
    async getData() {
      let response = await this.$http.get(this.apiName);
      console.log(response);
      if (response.ok) {
        this.roleList = response.data;
      }
    },
    editRole(role) {
      console.log(role);
      this.editDlgVisible = true;
      this.editForm = role;
    },
    async deleteRole(role) {
      await this.$confirm(`确认删除 ${role.name}？`);
      this.roleList = this.roleList.filter((v) => v.id != role.id);
    },
    onSubmit(formName) {
      this.$refs[formName].validate(async (valided) => {
        if (!valided) {
          return;
        }
        try {
          // let response = await this.$myhttp.post("UserRoles", this.addFrom);
          // console.log(response);

          // for (const key in this.addFrom) {
          //   if (Object.hasOwnProperty.call(this.addFrom, key)) {
          //     this.addFrom[key] = "";
          //   }
          // }
          console.log(this.editForm);
          let response = await this.$http.Put(
            this.apiName + "/" + this.editForm.roleId,
            this.editForm
          );
          console.log(response);
        } catch (error) {
          console.error(error);
          this.$message.error("修改失败");
        } finally {
          this.editDlgVisible = false;
        }
      });
    },
    addRoled(role) {
      console.log(role);
    },
    showSetRightDialog(role) {
      // console.log(this.$refs.treeRef.getCheckedKeys());
      //   递归获取三级节点的id
      console.log(role);
      this.getLeafkeys(role, this.defKeys);

      this.setRightDialogVisible = true;
      // this.defKeys = role.menu;
    },
    // 通过递归 获取角色下三级权限的 id, 并保存到defKeys数组
    getLeafkeys(node, arr) {
      // 没有children属性，则是三级节点
      if (!node.subMenus) {
        return arr.push(node.id);
      }
      node.subMenus.forEach((item) => this.getLeafkeys(item, arr));
    },
    findId(node, id) {
      if (node.subMenus) {
        let i = node.subMenus.findIndex((v) => v.id === id);
        if (i > -1) {
          node.subMenus.splice(i, 1);
        } else {
          node.subMenus.forEach((v) => this.findId(v, id));
        }
      }
    },
    async removeAuthById(role, authId) {
      console.log(role, authId);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "confirm") {
        this.findId(role, authId);
      } else {
        this.$message.info("删除失败!");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
  .center {
    display: flex;
    align-items: center;
    justify-content: space-around;
  }
  .el-tag {
    margin: 7px;
  }
  .bdbuttom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
}
</style>
